﻿using System;

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using PasswordSafe.Xml;
using System.Diagnostics;
using PasswordSafe.Classes;
using PasswordSafe.Themes;
using Fluid.Controls;
using Fluid.Classes;
using PasswordSafe.Encryption;
using PasswordSafe.Properties;

namespace PasswordSafe
{
    public partial class PasswordForm : Form
    {
        public PasswordForm()
        {
            Instance = this;
            Theme.Current = new DefaultTheme();
            InitializeComponent();
            Host.Bounds = Host.ClientBounds;
            Host.BackColor = Color.Empty;


            if (!DataReader.DataBaseExits())
            {
                WelcomeScreen welcome = new WelcomeScreen();
                welcome.Continue += new EventHandler(welcome_Continue);
                welcome.ShowMaximized(ShowTransition.None);
            }
            else
            {
                OpenLogin();
            }
        }


        void welcome_Continue(object sender, EventArgs e)
        {
            OpenLogin();
        }

        private void OpenLogin()
        {
            LoginPanel login = new LoginPanel(0, 0, 240, 400);
            this.Login = login;
            login.ConfirmPassword += new EventHandler<PasswordEventArgs>(login_PasswordVerify);
            login.ChangePassword += new EventHandler<HandledEventArgs>(login_ChangePassword);
            login.Enter += new EventHandler(login_Enter);
            login.EnsureEnterEnabled();
            login.ShowMaximized();
        }

        void login_ChangePassword(object sender, HandledEventArgs e)
        {
            bool match = false;
            string xml = Encryptor.Decrypt(EncryptedData, Login.Password);
            try
            {
                byte[] encrypted = Encryptor.Encrypt(xml, Login.NewPassword);
                string decrypted = Encryptor.Decrypt(encrypted, Login.NewPassword);
                match = decrypted == xml;
                if (match)
                {
                    DataReader.WriteData(encrypted);
                    EncryptedData = encrypted;
                }
            }
            catch
            {
            }
            e.Handled = match;
        }

        public byte[] EncryptedData
        {
            get
            {
                if (Encryptor.EncryptedData == null)
                {
                    Encryptor.EncryptedData = DataReader.ReadData();
                }
                return Encryptor.EncryptedData;
            }
            set { Encryptor.EncryptedData = value; }
        }

        private string xml = string.Empty;

        public LoginPanel Login;

        void login_Enter(object sender, EventArgs e)
        {
            Enter();
        }



        private void Enter()
        {
            Encryptor.Password = Login.Password;
            using (PasswordReader reader = new PasswordReader(xml))
            {
                ListBuilder.Instance = new ListBuilder(reader);
            }

            Browser = new Browser();
            Browser.Bounds = this.ClientRectangle;

            Browser.ShowMaximized(ShowTransition.FromBottom);
            Login.Text = "";
            Login.Visible = false;
        }

        void login_PasswordVerify(object sender, PasswordEventArgs e)
        {
            try
            {
                xml = Encryptor.Decrypt(EncryptedData, e.Password);
                e.Handled = xml.StartsWith("<?xml");
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                Debug.WriteLine(ex);
                e.Handled = false;
            }
        }

        public Browser Browser;
        public MessageDialog OKCancel;

        public static PasswordForm Instance;


        /// <summary>
        /// Only close, when the passwords are saved:
        /// </summary>
        /// <param name="e"></param>
        protected override void OnClosing(CancelEventArgs e)
        {
            if (Browser.Instance!=null && Browser.Instance.SavePasswords() == false) e.Cancel = true;
            base.OnClosing(e);
        }
    }
}